import pathToRegexp from 'path-to-regexp';
import { joinGroup,newGroup,smallGroupDetail,goodsDetailApi, couponlistApi, receiveCouponApi, getSpec, addCartOrBuy, favgoods, addRecord } from './api';
import { Toast } from 'antd-mobile';
import { routerRedux } from 'dva/router';
import {wxShare} from "../../utils/weixinShare";
import {IMAGE_DOMAIN,isWechat,GetQueryString} from "../../utils/common";
import {cancleGroup, groupIndex} from "../shopOpenGroup/api";
export default {
  namespace: 'goodsDetail',
  state: {
    goodsDetailInfo: {},
    select: [],
    editStatus: true,
    couponList: [],
      newGroupList: [],
      smallGroupDetailList: {},
    buyCount:1,
    cartCount: 0,
    recommended: "",
    specId: "",
  },
  reducers: {
    save(state, { data }) {
      return { ...state, ...data };
    },
      clearState() {
          return {
              smallGroupDetailList: {},};
      },
    receiveCoupon(state, { id }){

        const couponList =state.couponList.map((v,i,a)=>{
            if(v.id==id){
                return { ...v, isGet :1 }
            }else {
                return v
            }
        })

        return { ...state, couponList };
    },

    clearData(state) {
        state.goodsDetailInfo = {};
        state.buyCount = 1;
        state.cartCount = 0;
        return state;
    },
    clearSpecId(state) {
        state.specId = "";
        return state
    }
    // changeEditStatus(state,{  }){
    //   return {...state, editStatus: !state.editStatus }
    // },
    //
    // changeCartNum(state,{ index, listIndex, num }){
    //    const cartList= state.cartList;
    //     cartList[index].list[listIndex].goodsNum=num;
    //
    //   return {...state, cartList: cartList }
    // },


  },
  effects: {
    *goodsDetailEFF({ obj }, { put, call }) {
      const result = yield call(goodsDetailApi, obj);
      if (result.code == 200) {
        yield put({ type: 'save', data: { goodsDetailInfo: result.ret } });

        // Toast.success(result.msg, 1.5);
      } else {
          yield put({ type: 'save', data: { goodsDetailInfo: {} } });
      }
      return result
    },


    *couponlistEFF({ obj }, { put, call }) {
      const result = yield call(couponlistApi, obj);
      if (result.code == 200) {
        Toast.hide();
        yield put({ type: 'save', data: { couponList: result.ret.list || [] } });
      } else {

      }
    },

    *receiveCouponEFF({ obj }, { put, call }) {
      const result = yield call(receiveCouponApi, obj);
      if (result.code == 200) {
        Toast.hide();
        yield put({ type:'receiveCoupon', id:obj.id  })
      } else {

      }
    },

      *getSpecEFF({ index, selectIndex, v, obj }, { select, put, call }) {
          const goodsDetail = yield select((state)=>state.goodsDetail);
          const newSpeAll = goodsDetail.goodsDetailInfo.speAll;
          newSpeAll[v].list[index].isDefault=2;
          newSpeAll[v].list[selectIndex].isDefault=-1;
         // console.log(newSpeAll);
          //console.log(goodsDetail.goodsDetailInfo.speAll);
          let specSelectArr = Object.values(newSpeAll).map((v,i,a)=>{
              let rv =v.list.filter((vv,ii,aa)=>{
                      return vv.isDefault!=-1
              });
              // console.log(rv);
              if(rv.length>0){
                  return rv[0].spValueId
              }else {
                  return ""
              }
          });
         // Toast.loading('加载中...', 3);
          const result = yield call(getSpec, { goodsId:goodsDetail.goodsDetailInfo.id, specIds:specSelectArr.join(",") } );
          yield put({type: 'save', data: {specId: result.ret.specId || "qwerqwerqwerqwerqwerqwer"}});
          if (result.code == 200) {
              console.log(result)
              //Toast.info(result.success, 1.5);
              yield put({ type:'save',
                  data:{
                      specId: result.ret.specId,
                      goodsDetailInfo:{
                          ...goodsDetail.goodsDetailInfo,
                          speAll:newSpeAll,
                          restrictionNum:result.ret.restrictionNum,
                          spec:{
                              specGoodsStorage : result.ret.num,
                              specGoodsPrice:result.ret.price,
                              specId:result.ret.specId,
                              specGoodsSerial: result.ret.specGoodsSerial,
                              activityType:result.ret.activityType,
                              isActivity:result.ret.isActivity,
                              originalPrice:result.ret.originalPrice,
                              activityRuleId:result.ret.activityRuleId,
                              restrictionNum:result.ret.restrictionNum
                          },
                      }
              }})
          } else {

          }

      },

      *addCartOrBuyEFF({ obj }, { put, call, select }) {
          const goodsDetail = yield select((state)=>state.goodsDetail);
          const specId = yield select((state) => state.goodsDetail.specId);
          console.log(goodsDetail)
          console.warn(specId, "specId");
          const result = yield call(addCartOrBuy, { goodsId:goodsDetail.goodsDetailInfo.id, count:goodsDetail.buyCount, ...obj, specId: specId || goodsDetail.goodsDetailInfo.spec.specId });
          if (result.code == 200) {
              yield put({type: "save", data: {cartCount: result.ret.goodsNum}});
              if(obj.saveType==1){
                  yield put(routerRedux.push('/order'))
              }else {
                  Toast.success(result.msg, 1.5);
              }

          } else if(result.code == 500) {
              Toast.fail(result.msg, 1.5);
          }
      },

      *favgoodsEFF({ obj }, { put, call, select }) {
          const result = yield call(favgoods,  obj );
          if (result.code == 200) {
              const goodsDetail = yield select((state)=>state.goodsDetail);
              // Toast.success(result.msg,1.5);
              yield put({ type:'save',
                  data:{
                      goodsDetailInfo:{
                          ...goodsDetail.goodsDetailInfo,
                          isFav:obj.isFav
                          }
                      }
                  })

          } else {

          }
      },

      *emptyEFF({obj}, { put, call, select }) {
          yield put({type: 'clearData'});
          yield call(addRecord, obj);
      },
      //参加拼团
      *joinGroupEFF({ obj }, { put, call }) {
          Toast.loading('加载中...', 3);
          const result = yield call(joinGroup,obj);
          return result;
      },
      //获取最新拼团
      *newGroupEFF({ obj }, { put, call, select }) {
          const result = yield call(newGroup, { ...obj });
          if (result.code == 200) {
              if(result.ret==""){yield put({ type: 'save', data: { newGroupList:[]} })}else{
                  yield put({ type: 'save', data: {newGroupList:result.ret.list} });
              }
          }
          return result
      },
      //团信息(小窗口)
      *smallGroupDetailEFF({ obj }, { put, call, select }) {
          const result = yield call(smallGroupDetail, { ...obj });
          if (result.code == 200) {
              if(result.ret==""){yield put({ type: 'save', data: { smallGroupDetailList:{}} })}else{
                  yield put({ type: 'save', data: {smallGroupDetailList:result.ret} });
              }
          }
          return result
      },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        //console.log(match)
       if(pathname.includes('/goodsDetail/')){
          const match = pathToRegexp('/goodsDetail/:specId').exec(pathname);
          console.log(match[1].slice(0,32),match[1].slice(32))
          dispatch({ type:'goodsDetailEFF', obj:{ specId:match[1].slice(0,32),recommendId:match[1].slice(32), pageNo:1 } }).then(result=>{
              if(result.code==200){
                  // if(isWechat()){
                  if(match[1].slice(32)){
                      console.log(32)
                      wxShare(result.ret.sharedDistributeAddress ,IMAGE_DOMAIN+result.ret.image );
                  }else{
                      console.log(31)
                      wxShare(result.ret.sharedAddress ,IMAGE_DOMAIN+result.ret.image );
                  }
                    if(result.ret.activityType  ==110){
                        dispatch({ type:'newGroupEFF', obj:{ id:result.ret.id } })
                    }
                  // }
              }
          });
       }
      });
    },
  },
};
